import { createRouter, createWebHistory } from 'vue-router';
import ShowData from '@/views/showdata/showdata.vue'
import AiAnalyse from '@/views/aianalyse/aianalyse.vue'
import DisplayData from "@/views/chart/DisplayData.vue";
import DisplayChart from "@/views/chart/DisplayChart.vue";
import AuthLayout from '../views/authlayout/AuthLayout.vue'
import AddPreference from "../views/user/AddPreference.vue";
import UserPreferences from "@/views/user/UserPreferences.vue";
import PreferenceStats from "@/views/user/PreferenceStats.vue";
import EditPreference from '@/views/user/EditPreference.vue';
import ExportData from '@/views/showdata/exportdata.vue'

const routes = [
  {
    path: '/showdata',
    name: 'showdata',
    component: ShowData,
  },
  {
    path: '/exportdata',
    name: 'exportdata',
    component: ExportData,
  },
  {
    path: '/edit/:id',
    name: 'edit',
    component: EditPreference,
  },
  {
    path: '/aianalyse',
    name: 'aianalyse',
    component: AiAnalyse
  },
  {
    path: '/display-data',
    name:DisplayData,
    component: DisplayData
  },
  {
    path:"/display-chart",
    name: DisplayChart,
    component:DisplayChart
  },
  {
    path: '/user-preference',
    name:UserPreferences,
    component:UserPreferences
  },
  {
    path: '/stats/:userId',
    name:'stats',
    component:PreferenceStats,
    props:true
  },
  {
    path: '/add',
    name:'add',
    component: AddPreference,
    meta:{ fullPage: true }
  },
  {
    path: '/',
    component: AuthLayout,
    children: [
      {
        path: '',
        name: 'Login',
        component: () => import('@/views/login/Login.vue')
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/register/Register.vue')
      },
      {
        path: 'forgot-password',
        name: 'ForgotPassword',
        component: () => import('@/views/forgotpassword/ForgotPassword.vue')
      },
      // 添加一个捕获所有路由的规则
      {
        path: '/:pathMatch(.*)*',
        redirect: '/'
      }
    ]
  },
];
const router = createRouter({
  history: createWebHistory(),
  routes
});
router.beforeEach((to, from, next) => {
  const publicPaths = ['/', '/register', '/forgot-password'];

  // 精确匹配路径（排除子路径）
  const isPublicPath = publicPaths.includes(to.path);

  const authRequired = !isPublicPath;

  if (authRequired) {
    const token = localStorage.getItem("token");
    if (!token) {
      return next({ path: '/' });
    }
  }
  next();
});



export default router;
